import axios from 'axios'
import router from '../router/router'
import Toast from 'muse-ui-toast'
import Cookie from 'js-cookie'

const http = axios.create({
    baseURL: process.env.BASE_API,
    withCredentials: true, // 设置跨域，不需要设置为false即可
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
    transformRequest: [function(data) {
        let newData = ''
        for (const k in data) {
            if (data.hasOwnProperty(k) === true) {
                newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&'
            }
        }
        return newData
    }],
    timeout: 5000 // 请求超时时间
})

function apiAxios(method, url, params, response) {
    return http({
        method: method,
        url: url,
        data: method === 'POST' || method === 'PUT' ? params : null,
        params: method === 'GET' || method === 'DELETE' ? params : null
    })
}

// response 拦截器
http.interceptors.response.use(
    function(response) {

        if (response && response.data && response.data.code !== 1000) {
            Toast.error(response.data.message)
        }
        if (response && response.data && response.data.code === 1001) {
            Cookie.remove('user_id')
            Cookie.remove('username')
            Cookie.remove('session_id')
        }
        return response.data
    },
    error => {

        router.push('/404')
        Toast.error(error.message)
        return Promise.reject(error)
    }
)

export default {
    get: function(url, params, response) {
        return apiAxios('GET', url, params, response)
    },
    post: function(url, params, response) {
        return apiAxios('POST', url, params, response)
    },
    put: function(url, params, response) {
        return apiAxios('PUT', url, params, response)
    },
    delete: function(url, params, response) {
        return apiAxios('DELETE', url, params, response)
    }
}